package com.nwpu.am.intercepter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.nwpu.am.constant.JwtClaimsConstant;
import com.nwpu.am.constant.properties.JwtProperties;
import com.nwpu.am.exception.BizException;
import com.nwpu.am.pojo.entity.User;
import com.nwpu.am.utils.JwtUtil;
import com.nwpu.am.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;


/**
 * JwtProperties
 * <p>
 * jwt令牌校验的拦截器
 *
 * @author Roy
 * @version 1.0
 * {@code @date} 2024/6/3
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            // 当前拦截到的不是动态方法，直接放行
            return true;
        }

        // 1、从请求头中获取令牌
        String token = request.getHeader("Authorization");

        // 2、校验令牌
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        if (operations.get(token) == null) {
            response.setStatus(401);

            return false;
        }
        try {
            log.info("jwt校验token:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            // 将 LinkedHashMap 转换为 User 对象
            LinkedHashMap<String, Object> userMap = (LinkedHashMap<String, Object>) claims.get(JwtClaimsConstant.USER_INFO);
            User user = objectMapper.convertValue(userMap, User.class);
            log.info("当前员工user：{}", user);
            ThreadLocalUtil.set(user);
            // 3、通过，放行
            return true;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            // 4、不通过，响应401状态码
            response.setStatus(401);

            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
